// 更新货位数据脚本
const warehouseConfig = require('./src/config/warehouseConfig');
const db = require('./src/config/database');

// 从配置文件更新货位数据
function updateLocationsFromConfig() {
    console.log('开始更新货位数据...');
    
    // 删除所有现有货位数据
    db.run("DELETE FROM locations", (err) => {
        if (err) {
            console.error('删除现有货位数据失败:', err.message);
            return;
        }
        
        console.log('已删除现有货位数据');
        
        // 重新生成货位数据
        const locations = [];
        const warehouseCode = warehouseConfig.warehouse.code;
        
        // 遍历所有巷道
        warehouseConfig.aisles.forEach(aisle => {
            const aisleCode = aisle.code;
            
            // 生成该巷道的所有货位
            for (let r = 1; r <= aisle.rows; r++) {
                for (let c = 1; c <= aisle.columns; c++) {
                    for (let l = 1; l <= aisle.levels; l++) {
                        const locationCode = `${warehouseCode}-${aisleCode}-${r.toString().padStart(2, '0')}-${c.toString().padStart(2, '0')}-${l.toString().padStart(2, '0')}`;
                        locations.push({
                            location_code: locationCode,
                            aisle: aisleCode,
                            row: r.toString().padStart(2, '0'),
                            column: c.toString().padStart(2, '0'),
                            level: l.toString().padStart(2, '0'),
                            status: 'enabled'
                        });
                    }
                }
            }
        });
        
        // 插入货位数据
        if (locations.length > 0) {
            const stmt = db.prepare("INSERT INTO locations (location_code, aisle, row, column, level, status) VALUES (?, ?, ?, ?, ?, ?)");
            locations.forEach(loc => {
                stmt.run(loc.location_code, loc.aisle, loc.row, loc.column, loc.level, loc.status);
            });
            stmt.finalize();
            console.log(`成功更新了 ${locations.length} 个货位`);
        }
        
        // 关闭数据库连接
        db.close((err) => {
            if (err) {
                console.error('关闭数据库连接失败:', err.message);
            } else {
                console.log('数据库连接已关闭');
            }
        });
    });
}

// 执行更新
updateLocationsFromConfig();